"""
集成PPT生成服务
整合所有组件，提供完整的PPT生成流程，包括进度跟踪和实时状态更新。
"""

import logging
import asyncio
import uuid
from typing import Dict, List, Optional, Any
from datetime import datetime

from ..models import PPTRequest, SlideContent, GenerationSession
from .progress_tracker import progress_tracker, ProgressStage
from .content_generator import content_generator
from .ppt_generator import ppt_generator
from .template_manager import template_manager

logger = logging.getLogger(__name__)


class IntegratedPPTService:
    """
    集成PPT生成服务类
    
    提供完整的PPT生成流程，包括内容生成、样式应用和进度跟踪
    """
    
    def __init__(self):
        """初始化集成PPT生成服务"""
        self.progress_tracker = progress_tracker
        self.content_generator = content_generator
        self.ppt_generator = ppt_generator
        self.template_manager = template_manager
    
    async def generate_ppt_async(
        self,
        request: PPTRequest,
        session_id: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        异步生成PPT
        
        Args:
            request: PPT生成请求
            session_id: 会话ID，如果不提供则自动生成
            
        Returns:
            Dict: 生成结果
        """
        # 生成会话ID
        if not session_id:
            session_id = f"ppt_{uuid.uuid4().hex[:12]}"
        
        try:
            # 开始生成会话
            session = await self.progress_tracker.start_session(
                session_id=session_id,
                total_slides=request.slide_count,
                template_id=request.template_style
            )
            
            logger.info(f"开始PPT生成 - 会话: {session_id}, 主题: {request.topic}")
            
            # 第1阶段：初始化
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.INITIALIZING,
                stage_progress=0.5,
                message="正在初始化生成环境..."
            )
            
            # 验证模板
            template_config = self.template_manager.get_template(request.template_style)
            if not template_config:
                raise Exception(f"模板不存在: {request.template_style}")
            
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.INITIALIZING,
                stage_progress=1.0,
                message="初始化完成"
            )
            
            # 第2阶段：生成大纲
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.GENERATING_OUTLINE,
                stage_progress=0.1,
                message="AI正在分析主题和需求..."
            )
            
            outline_result = await self.content_generator.generate_presentation_outline(
                request=request,
                session_id=session_id
            )
            
            if not outline_result["success"]:
                raise Exception(f"大纲生成失败: {outline_result.get('error', '未知错误')}")
            
            outline = outline_result["outline"]
            slides_info = outline.get("slides", [])
            
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.GENERATING_OUTLINE,
                stage_progress=1.0,
                message=f"大纲生成完成，共 {len(slides_info)} 张幻灯片"
            )
            
            # 第3阶段：生成幻灯片内容
            slides_content = []
            total_slides = len(slides_info)
            
            for i, slide_info in enumerate(slides_info):
                current_slide = i + 1
                slide_title = slide_info.get("title", f"幻灯片 {current_slide}")
                
                # 更新幻灯片进度
                await self.progress_tracker.update_slide_progress(
                    session_id=session_id,
                    current_slide=current_slide,
                    total_slides=total_slides,
                    slide_title=slide_title
                )
                
                # 构建上下文
                context = {
                    "presentation_topic": request.topic,
                    "slide_number": current_slide,
                    "total_slides": total_slides,
                    "template_style": request.template_style,
                    "previous_slide": slides_info[i-1].get("title") if i > 0 else None,
                    "next_slide": slides_info[i+1].get("title") if i < len(slides_info)-1 else None
                }
                
                # 生成详细内容
                content_result = await self.content_generator.generate_slide_content(
                    slide_info=slide_info,
                    context=context,
                    session_id=session_id
                )
                
                if content_result["success"]:
                    slides_content.append(content_result["slide"])
                else:
                    logger.warning(f"幻灯片内容生成失败: {slide_title}")
                    # 使用基础内容作为后备
                    from ..models import SlideType
                    fallback_slide = SlideContent(
                        title=slide_title,
                        content=slide_info.get("content", []),
                        slide_type=SlideType(slide_info.get("type", "content")),
                        notes=slide_info.get("notes", ""),
                        slide_number=current_slide
                    )
                    slides_content.append(fallback_slide)
            
            # 第4阶段：应用模板样式
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.APPLYING_TEMPLATE,
                stage_progress=0.5,
                message=f"应用 {request.template_style} 模板样式..."
            )
            
            # 这里模板样式会在PPT生成阶段自动应用
            await asyncio.sleep(0.5)  # 模拟处理时间
            
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.APPLYING_TEMPLATE,
                stage_progress=1.0,
                message="模板样式应用完成"
            )
            
            # 第5阶段：生成PPT文件
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.GENERATING_PPT,
                stage_progress=0.2,
                message="正在创建PPT文件..."
            )
            
            # 生成PPT文件
            file_path = self.ppt_generator.create_presentation(
                slides=slides_content,
                template_id=request.template_style,
                title=outline.get("title", request.topic)
            )
            
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.GENERATING_PPT,
                stage_progress=1.0,
                message="PPT文件生成完成"
            )
            
            # 第6阶段：最终处理
            await self.progress_tracker.update_progress(
                session_id=session_id,
                stage=ProgressStage.FINALIZING,
                stage_progress=0.5,
                message="正在进行最终处理..."
            )
            
            # 完成生成
            await self.progress_tracker.complete_session(
                session_id=session_id,
                file_path=file_path,
                slides_count=len(slides_content)
            )
            
            # 返回结果
            result = {
                "success": True,
                "session_id": session_id,
                "file_path": file_path,
                "slides_count": len(slides_content),
                "template_id": request.template_style,
                "generated_at": datetime.now().isoformat(),
                "outline": outline,
                "message": "PPT生成成功"
            }
            
            logger.info(f"PPT生成完成 - 会话: {session_id}, 文件: {file_path}")
            return result
            
        except Exception as e:
            logger.error(f"PPT生成失败 - 会话: {session_id}, 错误: {e}")
            
            # 设置错误状态
            await self.progress_tracker.set_error(
                session_id=session_id,
                error_message=str(e),
                error_code="GENERATION_FAILED"
            )
            
            return {
                "success": False,
                "session_id": session_id,
                "error": str(e),
                "error_code": "GENERATION_FAILED",
                "message": "PPT生成失败"
            }
    
    async def get_generation_status(self, session_id: str) -> Dict[str, Any]:
        """
        获取生成状态
        
        Args:
            session_id: 会话ID
            
        Returns:
            Dict: 状态信息
        """
        session = self.progress_tracker.get_session(session_id)
        
        if not session:
            return {
                "success": False,
                "error": "会话不存在",
                "session_id": session_id
            }
        
        return {
            "success": True,
            "session_id": session_id,
            "status": session.status.value,
            "progress": session.progress,
            "current_step": session.current_step.value,
            "created_at": session.created_at.isoformat(),
            "updated_at": session.updated_at.isoformat(),
            "file_path": session.file_path,
            "error_message": session.error_message
        }
    
    async def cancel_generation(self, session_id: str) -> Dict[str, Any]:
        """
        取消生成
        
        Args:
            session_id: 会话ID
            
        Returns:
            Dict: 取消结果
        """
        session = self.progress_tracker.get_session(session_id)
        
        if not session:
            return {
                "success": False,
                "error": "会话不存在",
                "session_id": session_id
            }
        
        await self.progress_tracker.cancel_session(session_id)
        
        return {
            "success": True,
            "session_id": session_id,
            "message": "生成已取消"
        }
    
    def get_all_sessions(self) -> Dict[str, Any]:
        """
        获取所有活跃会话
        
        Returns:
            Dict: 所有会话信息
        """
        sessions = self.progress_tracker.get_all_sessions()
        
        sessions_info = {}
        for session_id, session in sessions.items():
            sessions_info[session_id] = {
                "status": session.status.value,
                "progress": session.progress,
                "current_step": session.current_step.value,
                "created_at": session.created_at.isoformat(),
                "updated_at": session.updated_at.isoformat(),
                "file_path": session.file_path,
                "error_message": session.error_message
            }
        
        return {
            "success": True,
            "sessions": sessions_info,
            "total_count": len(sessions_info)
        }
    
    def cleanup_old_sessions(self, max_age_hours: int = 24):
        """
        清理旧会话
        
        Args:
            max_age_hours: 最大保留时间（小时）
        """
        self.progress_tracker.cleanup_old_sessions(max_age_hours)


# 全局集成PPT生成服务实例
integrated_ppt_service = IntegratedPPTService()